package com.crazy.web.service.user.impl;

import cn.hutool.core.exceptions.ValidateException;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.crazy.model.major.entity.TUser;
import com.crazy.model.major.service.TUserService;
import com.crazy.web.service.user.RegisterService;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author zhaochaofeng
 * @version 1.0
 * @date 2020/11/18 14:48
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private TUserService tUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void register(String userName, String password) {
        //判定userName是否有重复
        QueryWrapper<TUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(TUser.Columns.userName, userName);
        List<TUser> tUsers = tUserService.list(queryWrapper);
        if(tUsers==null || tUsers.isEmpty()){
            TUser tUser = new TUser();
            tUser.setUserName(userName);
            tUser.setCreateTime(LocalDateTime.now());
            tUser.setUpdateTime(LocalDateTime.now());
            tUserService.save(tUser);
            tUser.setPassword(new SimpleHash("md5",password, ByteSource.Util.bytes(tUser.getId().toString()),20).toString());
            tUserService.updateById(tUser);
        }else {
            throw new ValidateException("该用户名已经存在");
        }
    }

}
